package com.pn.warehouse.service.impl;

import com.alibaba.fastjson.JSON;
import com.pn.warehouse.entity.Auth;
import com.pn.warehouse.mapper.AuthMapper;
import com.pn.warehouse.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@CacheConfig(cacheNames = "com.pn.warehouse.service.impl.AuthServiceImpl")
@Service
public class AuthServiceImpl implements AuthService {

    @Resource
    private AuthMapper authMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    //根据useId查询用户权限下的所有菜单
    @Override
    public List<Auth> findAuthByID(Integer userId) {
        //1、从redis中查询是否含有用户菜单树
        String authTreeJson = redisTemplate.opsForValue().get("authTree" + userId);

        //2、如果存在，将查出的json串转成List<Auth>对象并返回
        if (StringUtils.hasText(authTreeJson)){
            List<Auth> authTreeList = JSON.parseArray(authTreeJson, Auth.class);
            return authTreeList;
        }

        //3、如果不存在，从数据库中查询该用户权限下的所有菜单
        List<Auth> allAuthList = authMapper.findAuthByID(userId);
        //4、将所有的菜单List<Auth>转成菜单树List<Auth>（就是把转成list套list的形式）
        List<Auth> authTreeList = allAuthToAuthTree(allAuthList, 0);
        //5、向redis缓存用户的菜单树 —— 键为：authTree+userId；值为List<Auth>的转的json串，然后返回菜单树
        redisTemplate.opsForValue().set("authTree" + userId, JSON.toJSONString(authTreeList),28800, TimeUnit.SECONDS);
        return authTreeList;
    }

    //将所有的菜单List<Auth>转成菜单树List<Auth>的方法
    private List<Auth> allAuthToAuthTree(List<Auth> allAuthList, Integer pid){
        //查询出所有当前菜单的一级菜单
        List<Auth> firstList = new ArrayList<>();
        for (Auth auth : allAuthList) {
            if (Integer.valueOf(auth.getParentId()).equals(pid)){
                firstList.add(auth);
            }
        }

        //拿到每个当前菜单的二级菜单
        for (Auth auth : firstList) {
            List<Auth> secondList = allAuthToAuthTree(allAuthList, auth.getAuthId());
            auth.setChildAuth(secondList);
        }

        return firstList;
    }

    //查询所有的权限菜单树
    @Cacheable(key = "'all:authTree'")
    @Override
    public List<Auth> findAllAuthTree() {
        //1、查出所有的权限
        List<Auth> allAuthList = authMapper.findAllAuth();
        //2、转成菜单树并返回
        List<Auth> authTreeList = allAuthToAuthTree(allAuthList, 0);
        return authTreeList;
    }

}
